/**
 * 目录(Table of Contents)组件
 * Phase 1: 前端 MVP 使用
 * 
 * 功能：
 * - 自动提取 Markdown 标题
 * - 滚动高亮
 * - 点击跳转
 * - 层级缩进
 */

import React, { useState, useEffect, useCallback } from 'react';
import { cn } from '@/lib/utils';
import { List, ArrowUp } from 'lucide-react';
import { ScrollArea } from '@/components/ui/scroll-area';

const TableOfContents = ({
  content,
  className = '',
  scrollOffset = 80,
  isFullscreen = false // 是否在全屏模式
}) => {
  const [headings, setHeadings] = useState([]);
  const [activeId, setActiveId] = useState('');
  const [showBackToTop, setShowBackToTop] = useState(false);

  // 从 DOM 提取标题（而不是从 Markdown 文本）
  useEffect(() => {
    if (!content) {
      setHeadings([]);
      return;
    }

    // 延迟提取，确保 DOM 已渲染
    const timer = setTimeout(() => {
      const headingElements = document.querySelectorAll('article h1, article h2, article h3, article h4, article h5, article h6');

      const toc = Array.from(headingElements).map((el, index) => {
        const level = parseInt(el.tagName.substring(1)); // H2 -> 2
        const text = el.textContent || '';
        const id = el.id || `heading-${index}`;

        return {
          id,
          level,
          text,
          index
        };
      });

      setHeadings(toc);
    }, 300); // 延迟 300ms 确保 Markdown 已渲染

    return () => clearTimeout(timer);
  }, [content]);

  // 监听滚动，高亮当前标题，同时检测是否需要显示返回顶部
  useEffect(() => {
    if (headings.length === 0) return;

    // 检测滚动容器
    const fullscreenContainer = document.getElementById('fullscreen-container');
    const scrollContainer = fullscreenContainer || window;

    const handleScroll = () => {
      // 更新返回顶部按钮显示状态
      if (isFullscreen) {
        // 全屏模式：监听 fullscreen-container 的滚动
        if (fullscreenContainer) {
          setShowBackToTop(fullscreenContainer.scrollTop > 300);
        }
      } else {
        // 正常模式：监听 window 的滚动
        setShowBackToTop(window.scrollY > 300);
      }

      // 获取所有标题元素
      const headingElements = headings
        .map(h => document.getElementById(h.id))
        .filter(Boolean);

      if (headingElements.length === 0) return;

      // 获取当前滚动位置
      const scrollTop = fullscreenContainer
        ? fullscreenContainer.scrollTop + 100  // 全屏模式
        : window.scrollY + 100;                // 正常模式

      for (let i = headingElements.length - 1; i >= 0; i--) {
        const element = headingElements[i];
        if (element && element.offsetTop <= scrollTop) {
          setActiveId(headings[i].id);
          return;
        }
      }

      // 如果都没有匹配，默认第一个
      setActiveId(headings[0].id);
    };

    // 初始化
    handleScroll();

    // 监听滚动事件（防抖）
    let timeoutId;
    const debouncedScroll = () => {
      clearTimeout(timeoutId);
      timeoutId = setTimeout(handleScroll, 50);
    };

    scrollContainer.addEventListener('scroll', debouncedScroll);
    return () => {
      scrollContainer.removeEventListener('scroll', debouncedScroll);
      clearTimeout(timeoutId);
    };
  }, [headings, isFullscreen]);

  // 点击跳转
  const handleClick = useCallback((e, id) => {
    e.preventDefault();

    const element = document.getElementById(id);
    if (element) {
      // 检测滚动容器（全屏模式 vs 正常模式）
      const fullscreenContainer = document.getElementById('fullscreen-container');

      if (fullscreenContainer) {
        // 全屏模式：滚动容器本身
        const top = element.offsetTop - scrollOffset;
        fullscreenContainer.scrollTo({
          top,
          behavior: 'smooth'
        });
      } else {
        // 正常模式：window 滚动
        const top = element.offsetTop - scrollOffset;
        window.scrollTo({
          top,
          behavior: 'smooth'
        });
      }

      // 更新 URL hash
      window.history.pushState(null, '', `#${id}`);
      setActiveId(id);
    }
  }, [scrollOffset]);

  // 返回顶部函数
  const scrollToTop = useCallback(() => {
    const fullscreenContainer = document.getElementById('fullscreen-container');

    if (isFullscreen && fullscreenContainer) {
      // 全屏模式：滚动 fullscreen-container
      fullscreenContainer.scrollTo({
        top: 0,
        behavior: 'smooth'
      });
    } else {
      // 正常模式：滚动 window
      window.scrollTo({
        top: 0,
        behavior: 'smooth'
      });
    }
  }, [isFullscreen]);

  // 如果没有标题，不渲染
  if (headings.length === 0) {
    return null;
  }

  // 只显示 H2 和 H3（H1 通常是页面标题）
  const filteredHeadings = headings.filter(h => h.level >= 2 && h.level <= 3);

  if (filteredHeadings.length === 0) {
    return null;
  }

  return (
    <nav
      className={cn(
        "w-full",
        className
      )}
    >
      <div className="sticky top-20">
        {/* 标题 */}
        <div className="flex items-center gap-2 mb-4 px-3">
          <List className="size-4 text-muted-foreground" />
          <h3 className="font-semibold text-sm text-foreground">
            目录
          </h3>
        </div>

        {/* 目录列表 */}
        <ScrollArea className="h-[calc(100vh-200px)]">
          <ul className="space-y-0.5 text-sm">
            {filteredHeadings.map((heading) => {
              const isActive = activeId === heading.id;
              const indent = (heading.level - 2) * 12; // 12px 每级

              return (
                <li
                  key={heading.id}
                  style={{ paddingLeft: `${indent}px` }}
                  className="relative"
                >
                  <a
                    href={`#${heading.id}`}
                    onClick={(e) => handleClick(e, heading.id)}
                    className={cn(
                      "block py-1.5 px-3 rounded-md transition-all",
                      "hover:text-primary hover:bg-accent",
                      "break-words",
                      isActive
                        ? "text-primary font-medium border-l-2 border-primary bg-primary/5"
                        : "text-muted-foreground"
                    )}
                    title={heading.text}
                  >
                    <span className="line-clamp-2 break-words text-xs">
                      {heading.text}
                    </span>
                  </a>
                </li>
              );
            })}
          </ul>
        </ScrollArea>

        {/* 提示和返回顶部 */}
        <div className="mt-4 px-3 space-y-2">
          <p className="text-xs text-muted-foreground">
            💡 点击标题快速跳转
          </p>
          {showBackToTop && (
            <button
              onClick={scrollToTop}
              className={cn(
                "w-full flex items-center justify-center gap-1.5 text-xs",
                "text-primary hover:text-primary/80",
                "font-medium transition-colors",
                "py-1.5 px-2 rounded-md",
                "hover:bg-accent/50"
              )}
              title="返回顶部"
            >
              <ArrowUp className="size-3.5" />
              <span>返回顶部</span>
            </button>
          )}
        </div>
      </div>
    </nav>
  );
};

export default TableOfContents;

